<template>
  <div>
    <el-form ref="form" :model="spu" label-width="80px">
      <el-form-item label="Spu名称">
        <el-input v-model="spu.spuName" placeholder="请输入spu名称"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :label="tm.tmName"
            :value="tm.id"
            v-for="tm in tradeMarkList"
            :key="tm.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          type="textarea"
          rows="4"
          placeholder="请输入spu描述"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <!--on-preview:图片预览的时候触发 on-remove:当删除图片时候触发 file-list-->
      <el-form-item label="SPU图片">
        <el-upload
          :file-list="spuImageList" action="/api/admin/product/fileUpload" list-type="picture-card"
          :on-success="handlderSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select :placeholder="`还有${unSelectSaleAttr.length}个未选择销售属性`" v-model="attrIdAndAttrName">
          <el-option :label="unSelect.name" :value="`${unSelect.id}:${unSelect.name}`" v-for="unSelect in unSelectSaleAttr" :key="unSelect.id"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-plus" :disabled="!attrIdAndAttrName" @click="addSaleAttr">添加销售属性</el-button>
        <!--展示的是当前spu属于自己的销售属性-->
        <el-table border style="width: 100%" :data="spu.spuSaleAttrList">
          <el-table-column
            align="center"
            label="序号"
            type="index"
            width="80px"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row }">
              <el-tag  v-for="(tag,index) in row.spuSaleAttrValueList" closable :disable-transitions="false" :key="tag.id" 
              @close="row.spuSaleAttrValueList.splice(index,1)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag" v-if="row.inputVisible" v-model="row.inputValue" ref="saveTagInput" @blur="handlerInputConfirm(row)" size="small">
              </el-input>
              <el-button v-else class="button-new-tag"  size="small" @click="addSaleAttrValue(row)">添加</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="width"> 
            <template slot-scope="{row}">
              <el-button type="danger" icon="el-icon-delete" size="mini"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="addOrUpdateSpu" type="primary">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      //spu初始化是一个空对象 存储spu信息属性
      spu: {
        //三级分类的id
        category3Id: 0,
        //描述
        description: "",
        spuName: "",
        //品牌的id
        tmId: "",
        //spu图片信息
        spuImageList: [
          {
            id: 0,
            imgName: "",
            imgUrl: "",
            spuId: 0,
          },
        ],
        //品台属性与属性值的收集
        spuSaleAttrList: [
          // {
          //   baseSaleAttrId: 0,
          //   id: 0,
          //   saleAttrName: "string",
          //   spuId: 0,
          //   spuSaleAttrValueList: [
          //     {
          //       baseSaleAttrId: 0,
          //       id: 0,
          //       isChecked: "string",
          //       saleAttrName: "string",
          //       saleAttrValueName: "string",
          //       spuId: 0,
          //     },
          //   ],
          // },
        ],
      },
      tradeMarkList: [], //存储品牌信息
      spuImageList: [], //存储spu图片信息
      saleAttrList: [], // 销售属性信息
      attrIdAndAttrName:'',//收集未选择的销售属性的id
    };
  },
  methods: {
    cancel(){
      //切换场景
      this.$emit('changeScene', {scene:0,flag:''})
      //清理数据
      //Object.assign : es6合并对象的方法
      //组件this._data可以操作data当中的响应式数据
      //this.$options可获取配置对象 配置对象的data函数返回的是初始对象
      Object.assign(this._data,this.$options.data())
    },
    async addOrUpdateSpu(){
      //整理参数
      this.spu.spuImageList = this.spuImageList.map(item=>{
        return{
          imgName:item.name,
          imgUrl:(item.response&&item.response.data)||item.url  
        }
      })
      const result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if(result.code==200){
        this.$message({type:'success',message:'保存成功'})
        //通知父组件
        this.$emit('changeScene', {scene:0,flag:this.spu.id})
      }
    },
    //el-button失去焦点
    handlerInputConfirm(row){
     row.inputVisible = false
     //结构处销售属性收集的数据
     //新增的销售属性值
     const {baseSaleAttrId,inputValue} = row
     if(inputValue.trim()==''){
      this.$message("属性值不能为空")
      return 
     }
     //属性值不能重复
     const isEquqals = row.spuSaleAttrValueList.every(item=>item.saleAttrValueName!=inputValue)
     if(!isEquqals) return 
     const newSaleAttrValue = {baseSaleAttrId,saleAttrValueName:inputValue}
     row.spuSaleAttrValueList.push(newSaleAttrValue)
    },
    //添加按钮 button变为input
    addSaleAttrValue(row){
      //挂载在销售属性值控制button与input
      this.$set(row,'inputVisible',true)
      //通过响应式数据inputValue收集新增的属性值
      this.$set(row,'inputValue','')
    },
    //添加销售属性
    addSaleAttr(){
     const[baseSaleAttrId,saleAttrName] = this.attrIdAndAttrName.split(":")
     //向spu对象spuSaleAttrList属性添加新的销售属性
     const newSaleAttr = {baseSaleAttrId,saleAttrName,spuSaleAttrValueList:[]}
     //添加新的销售属性
     this.spu.spuSaleAttrList.push(newSaleAttr)
     //清空数据
     this.attrIdAndAttrName=''
    },
    //图片上传成功回调
    handlderSuccess(response,file,fileList){
     this.spuImageList = fileList
    },
    //照片墙删除某一个图片会触发
    handleRemove(file, fileList) {
     //收集照片墙
     this.spuImageList = fileList //因为照片墙必须有img url而服务器不需要这两个字段
    },
    //照片墙图片预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //初始化spuForm数据
    async initSpuData(spu) {
       const spuResult = await this.$API.spu.getSpuById(spu.id);
      if (spuResult.code == 200) {
        //在点击修改时
        this.spu = spuResult.data;
      }
    
      //获取spu图片的数据
      const spuImageResult = await this.$API.spu.getSpuImage(spu.id);
      if (spuImageResult.code == 200) {
        //element-ui图片墙展示需要数组,数组需要url name属性,而我们后台没有这个两个属性需要处理系
        let listArr = spuImageResult.data;
        listArr.forEach((item) => {
          (item.name = item.imgName), (item.url = item.imgUrl);
        });
        this.spuImageList = listArr;
      }
        //获取品牌的信息
      const tradeMarkResult = await this.$API.spu.getTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取品牌全部销售属性
      const spuSaleAttrResult = await this.$API.spu.getSaleAttrList();
      if (spuSaleAttrResult.code == 200) {
        this.saleAttrList = spuSaleAttrResult.data;
      }
    },
    async addSpuInIt(category3Id){
      //清除数据
      Object.assign(this._data,this.$options.data())
      //添加spu收集三级分类id
      this.spu.category3Id = category3Id
       //获取品牌的信息
      const tradeMarkResult = await this.$API.spu.getTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }
      //获取品牌全部销售属性
      const spuSaleAttrResult = await this.$API.spu.getSaleAttrList();
      if (spuSaleAttrResult.code == 200) {
        this.saleAttrList = spuSaleAttrResult.data;
      }
    }
  },
  computed: {
    //计算还未选择的销售属性
    unSelectSaleAttr(){
      //整个品台的销售属性一共三个 颜色 尺寸 版本
      const result = this.saleAttrList.filter(item=>{
        return this.spu.spuSaleAttrList.every(item1=>{
          return item.name!=item1.saleAttrName
        })
      })
      return result
    }
  }
};
</script>

<style>
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
